package com.ming.dancing.springboot.controller;


import com.ming.dancing.springboot.entity.Dancer;
import com.ming.dancing.springboot.entity.Files;


import com.ming.dancing.springboot.service.DancerService;
import com.ming.dancing.springboot.service.FilesService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.Id;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.io.*;
@Controller
public class FileController {

    @Autowired
    FilesService filesService;
    @Autowired
    DancerService dancerService;
    /**
     * 返回当前用户的所有文件列表---json格式数据
     */
    @GetMapping("findAllJSON")
    @ResponseBody
    public List<Files> findAllJSON(Model model) {
        //根据用户id查询有的文件信息
        List<Files> files = filesService.findallFile();
        System.out.println("json返回信息");
        return files;
    }
    /**
     * 删除文件信息
     */
    @GetMapping("delete")
    public String delete(String id) throws FileNotFoundException {

        //根据id查询信息
        Files files = filesService.findById(id);
        //删除文件
        String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static" + files.getPath();
        File file = new File(realPath, files.getNewFileName());
        if(file.exists())file.delete();//立即删除

        //删除数据库中记录
        filesService.delete(id);

        return "redirect:/tofile";
    }
    /**
     * 文件下载
     */
    @GetMapping("download")
    public void download(String openStyle, String id, HttpServletResponse response) throws IOException {
        //获取打开方式
        openStyle = openStyle == null ? "attachment" : openStyle;
        //获取文件信息
        Files files = filesService.findById(id);
        //点击下载链接更新下载次数
        if ("attachment".equals(openStyle)) {
            files.setDowncounts(files.getDowncounts() + 1);
            filesService.update(files);
        }
        //根据文件信息中文件名字 和 文件存储路径获取文件输入流
        String realpath = ResourceUtils.getURL("classpath:").getPath() + "/static" + files.getPath();
        //获取文件输入流
        FileInputStream is = new FileInputStream(new File(realpath,files.getNewFileName()));
        //附件下载
        response.setHeader("content-disposition", openStyle + ";fileName=" + URLEncoder.encode(files.getOldFileName(), "UTF-8"));
        //获取响应输出流
        ServletOutputStream os = response.getOutputStream();
        //文件拷贝
        IOUtils.copy(is, os);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }

    /**
     * 上传文件处理 并保存文件信息到数据库中
     */
    @PostMapping("upload")
    public String upload(MultipartFile aaa, HttpSession session) throws IOException {

        //获取文件原始名称
        String oldFileName = aaa.getOriginalFilename();

        //获取文件后缀
        String extension = "." + FilenameUtils.getExtension(aaa.getOriginalFilename());

        //生成新的文件名称
        String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString().replace("-", "") + extension;
        System.out.println("新文件名"+newFileName);
        //文件大小
        Long size = aaa.getSize();

        //文件类型
        String type = aaa.getContentType();

        //处理根据日期生成目录
        String realPath = ResourceUtils.getURL("classpath:").getPath() + "static/files";
        String dateFormat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //String dateDirPath = uploadPath + "/files/" + dateFormat;
        String dateDirPath = realPath + "/" + dateFormat;
        System.out.println("日期生成目录"+realPath);

        java.io.File dateDir = new java.io.File(dateDirPath);
        if (!dateDir.exists()) dateDir.mkdirs();

        //处理文件上传
        aaa.transferTo(new java.io.File(dateDir, newFileName));

        //将文件信息放入数据库保存
        Files files = new Files();
        files.setOldFileName(oldFileName).setNewFileName(newFileName).setExt(extension).setSize(String.valueOf(size))
                .setType(type).setPath("/files/" + dateFormat);
        filesService.save(files);

        return "redirect:/tofile";
    }

//    文件查询
    @GetMapping("tofile")
    public String tofile(Model model)
    {
        List<Files> files = filesService.findallFile();
        model.addAttribute("files",files);
        return "dancer/file";
    }
    /**
     * 上传舞者照片
     */
    @PostMapping("/uploadDancer/{id}")
    public String uploadDancer(@PathVariable("id")Integer id, MultipartFile aaa, HttpSession session, Map<String,String>map) throws IOException {

        if(!aaa.isEmpty())
        {
            //获取文件原始名称
            String oldFileName = aaa.getOriginalFilename();
            //获取文件后缀
            String extension = "." + FilenameUtils.getExtension(aaa.getOriginalFilename());
            //生成新的文件名称
            String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString().replace("-", "") + extension;
            System.out.println("新文件名"+newFileName);

            //处理根据日期生成目录
            String realPath = ResourceUtils.getURL("classpath:").getPath() + "static/DancerImage";
            //String dateFormat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            //String dateDirPath = realPath + "/" + dateFormat;

            java.io.File dateDir = new java.io.File(realPath);
            if (!dateDir.exists()) dateDir.mkdirs();


            //处理文件上传
            aaa.transferTo(new java.io.File(dateDir, newFileName));
            System.out.println(realPath+"  "+id);
            //将文件信息放入数据库保存

            dancerService.setpicture(id,newFileName);
            System.out.println("添加照片成功");
            return "redirect:/emps";
        }
        else {
            System.out.println("进去~");
            map.put("msg","上传文件为空，请重新上传");
            return "redirect:/emps";
        }

    }
    /**
     * 显示舞蹈老师图片
     */
    @GetMapping("view")
    public void view(String picture, HttpServletResponse response) throws IOException {
        System.out.println(picture);
        //根据文件信息中文件名字 和 文件存储路径获取文件输入流
        String realpath = ResourceUtils.getURL("classpath:").getPath() + "/static/DancerImage/"  ;
        //获取文件输入流
        FileInputStream is = new FileInputStream(new File(realpath,picture));
        //附件下载
        response.setHeader("content-disposition",   "inline;fileName=" + URLEncoder.encode(picture, "UTF-8"));
        //获取响应输出流
        ServletOutputStream os = response.getOutputStream();
        //文件拷贝
        IOUtils.copy(is, os);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }
}
